<template>
  <div class="header">
    <!-- 折叠按钮 -->
    <div class="collapse-btn" @click="collapseChage">
      <i class="el-icon-menu"></i>
    </div>
    <div class="logo"><span class="time">TT</span>洗车后台管理系统</div>
    <span class="time">{{ currentDateTime }}<span style="font-family: LMQY;">&nbsp;{{ week }}</span></span>
    <div class="header-right">
      <div class="header-user-con">
        <!-- 全屏显示 -->
        <div class="btn-fullscreen" @click="handleFullScreen">
          <el-tooltip effect="dark" :content="fullscreen ? `取消全屏` : `全屏`" placement="bottom">
            <i class="el-icon-rank"></i>
          </el-tooltip>
        </div>
        <!-- 用户头像 -->
        <div class="user-avator">
          <el-avatar :size="35" :src="staffInfo.avatar"></el-avatar>
        </div>
        <!-- 用户名下拉菜单 -->
        <el-dropdown class="user-name" trigger="click" @command="handleCommand">
          <span class="el-dropdown-link">
            {{ loginName }}-<span style="font-family: A023;">{{ username }}</span>
            <i class="el-icon-caret-bottom"></i>
          </span>
          <el-dropdown-menu slot="dropdown" style="font-family: LMQY;">
            <el-dropdown-item divided command="open">个人中心</el-dropdown-item>
            <el-dropdown-item divided command="changePass">修改密码</el-dropdown-item>
            <!-- <el-dropdown-item @click="userToggle">切换账号</el-dropdown-item> -->
            <el-dropdown-item divided command="loginout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-row>
          <el-dialog title="修改个人信息" :visible.sync="dialogVisible" width="60%" :before-close="handleClose">
            <el-form :model="form" :rules="rules" ref="form" label-width="150px">
              <div class="updateinfo">
                <div class="left">
                  <el-form-item label="头像" prop="avatar">
                    <!-- <img
                      style="width: 150px; height: 110px"
                      :src="form.avatar" /> -->

                    <!--上传图片  -->
                    <el-upload action="http://localhost:16868/user/uploadFile" name="file1" :show-file-list="false"
                      :on-success="handleFileSuccess" :before-upload="beforeFileUpload">
                      <img :src="form.avatar" class="avatar" />
                    </el-upload>
                  </el-form-item>





                  <el-form-item label="昵称" prop="loginName">
                    <el-input v-model="form.loginName"></el-input>
                  </el-form-item>
                  <el-form-item label="性别" prop="sex">
                    <el-switch v-model="form.sex" active-color="#ff4949" inactive-color="#13ce66" active-text="女"
                      inactive-text="男" :active-value="0" :inactive-value="1">
                    </el-switch>
                  </el-form-item>
                </div>
                <div class="right">
                  <el-form-item label="用户编号" prop="userId">
                    <el-input v-model="form.userId" disabled></el-input>
                  </el-form-item>
                  <el-form-item label="账号" prop="userName">
                    <el-input v-model="form.userName" disabled></el-input>
                  </el-form-item>
                  <el-form-item label="创建时间" prop="userDate">
                    <el-input v-model="form.userDate" disabled></el-input>
                  </el-form-item>
                  <el-form-item label="手机号码" prop="phonenumber">
                    <el-input v-model="form.phonenumber"></el-input>
                  </el-form-item>
                </div>
              </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="handleClose">取 消</el-button>
              <el-button type="primary" @click="addOrUpdate">提 交</el-button>
            </span>
          </el-dialog>
        </el-row>
        <el-row>
          <el-dialog :title="title" :visible.sync="passFormVisible">
            <!-- :rules="rules" -->
            <el-form :model="upForm" status-icon :rules="rules" ref="upForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="原始密码" prop="passold">
                <el-input type="password" autocomplete="off" v-model="upForm.passold" @blur="checkOldPassword('upForm')"
                  show-password></el-input>
              </el-form-item>
              <el-form-item label="新的密码" prop="pass">
                <el-input type="password" v-model="upForm.pass" autocomplete="off" show-password></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="checkPass">
                <el-input type="password" v-model="upForm.checkPass" autocomplete="off" show-password></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm('upForm')" :disabled="btnStatus">提 交</el-button>
                <el-button @click="resetForm('upForm')" type="info">重 置</el-button>
                <el-button @click="(passFormVisible = false), clearValidate('upForm')">取 消</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script>
import bus from "./bus";
export default {
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.upForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else if (
        this.upForm.passold == this.upForm.pass ||
        value === this.upForm.passold
      ) {
        callback(new Error("不能和原密码一致!"));
      } else {
        callback();
      }
    };
    return {
      form: {
        userName: "",
      },
      rules: {
        userName: [
          { required: true, message: "昵称不能为空", trigger: "blur" },
        ],
      },
      dialogVisible: false,
      staffInfo: {}, //登录人信息对象
      currentDateTime: "", //获取当前时间
      week: "", //星期几
      collapse: false,
      fullscreen: false,
      message: 2,
     
      btnStatus: false,
      passFormVisible: false,
      title: "",
      upForm: { passold: "", pass: "", checkPass: "" },
      // 表单校验
      rules: {
        passold: [{ message: "", trigger: "blur" }],
        pass: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          {
            min: 3,
            max: 12,
            message: "长度在 3 到 12个字符",
            trigger: "blur",
          },
        ],
        checkPass: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { required: true, validator: equalToPassword, trigger: "blur" },
        ],
      },
    };
  },
  created: function () {
    // 调用两个方法，给头部导航栏gettime和week赋值
    this.currentTime();
    this.getWeek();
    this.loadData();
  },
  computed: {
    username() {
      let username = localStorage.getItem("ms_username");
      return username ? username : this.staffInfo.userName;
    },
    loginName() {
      let loginName = localStorage.getItem("ms_loginName");
      return loginName ? loginName : this.staffInfo.loginName;
    },
  },
  methods: {
    loadData() {
      var _this = this;
      this.$http
        .get("/user/queryById")
        .then(function (response) {
          console.log(response);
          //判断是否执行成功
          if (response.data.code == 200) {
            _this.staffInfo = response.data.data;
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    handleClose() {
      this.dialogVisible = false;
      this.$emit("flesh");
    },
    //实现用户添加或者更新
    addOrUpdate() {
      var _this = this;
      this.$http
        .post("/user/update", this.form)
        .then(function (response) {
          console.log(response);
          if (response.data.code == 200) {
            _this.$message({
              message: "操作成功",
              type: "success",
            });
            _this.dialogVisible = false;
            _this.loadData();
          } else {
            _this.$message("操作失败");
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    //头部导航获取当前时间
    getTime: function () {
      //获取当前时间
      let currentDate = new Date();
      //获取到4位的年 2022
      let yy = currentDate.getFullYear();
      let mm = currentDate.getMonth() + 1;
      let dd = currentDate.getDate();
      let hh = currentDate.getHours();
      //currentDate.getMinutes()<10    0-9   ->  00 - 09
      let mf =
        currentDate.getMinutes() < 10
          ? "0" + currentDate.getMinutes()
          : currentDate.getMinutes();
      let ss =
        currentDate.getSeconds() < 10
          ? "0" + currentDate.getSeconds()
          : currentDate.getSeconds();
      this.currentDateTime =
        yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
    },
    //每隔0.5秒调用getTime属性
    currentTime() {
      //setInterval(param1,param2)  每个param2间隔时间调回用方法param1
      setInterval(this.getTime, 500);
    },
    //获取星期几
    getWeek() {
      //java String   "abc".charAt(1)  返回某一个字符串"abc"1位置上的字符
      //.getDay() 获取星期几的数字 0-6    周日是第1天
      //.getDate() 获取档期日期的每月第几天   2020-03-12  12
      console.log("星期" + new Date().getDay());
      //charAt 返回指定字符串位置上的值  "abcdef".charAt(0) = a     "abcdef".charAt(2) = c
      this.week = "星期" + "日一二三四五六".charAt(new Date().getDay());
    },
    resetForm(upForm) {
      this.clearValidate("upForm");
      this.upForm = {};
    },
    checkOldPassword(upForm) {
      //获取用户登录后的信息
      var _this = this;
      this.$http
        .get("/user/queryByPassword?password=" + _this.upForm.passold)
        .then(function (response) {
          //alert(JSON.stringify(response));
          if (response.data.data != 200) {
            _this.$message.error("请输入正确的密码");
            //_this.rules.passold[0].message = "请输入正确的密码";
            _this.btnStatus = true;
          } else {
            _this.btnStatus = false;
          }
        });
    },
    clearValidate(formName) {
      this.$refs[formName].clearValidate();
    },
    submitForm(upForm) {
      var _this = this;
      this.$http
        .put("/user/alterPassword?pass=" + this.upForm.pass)
        .then(function (response) {
          if (response.data.code == 200 &&
            _this.upForm.pass == _this.upForm.checkPass &&
            _this.upForm.pass != _this.upForm.passold) {
            // //提示修改成功
            _this.$message({
              message: "恭喜你，这是一条成功消息",
              type: "success",
            });
            localStorage.removeItem("token");
            _this.$router.push("/Login");
          }
        });
    },


    // 用户名下拉菜单选择事件
    handleCommand(command) {
      //个人中心
      if (command == "open") {
        this.form = this.staffInfo;
        this.dialogVisible = true;
        //指定对话框标题
        this.title = "个人信息";
      }
      //修改密码
      if (command == "changePass") {
        this.passFormVisible = true;
      }

      //退出
      if (command == "loginout") {
        localStorage.removeItem("token");
        this.$router.push("/Login");
      }
    },
    // 侧边栏折叠
    collapseChage() {
      this.collapse = !this.collapse;
      bus.$emit("collapse", this.collapse);
    },
    // 全屏事件
    handleFullScreen() {
      let element = document.documentElement;
      if (this.fullscreen) {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      } else {
        if (element.requestFullscreen) {
          element.requestFullscreen();
        } else if (element.webkitRequestFullScreen) {
          element.webkitRequestFullScreen();
        } else if (element.mozRequestFullScreen) {
          element.mozRequestFullScreen();
        } else if (element.msRequestFullscreen) {
          // IE11
          element.msRequestFullscreen();
        }
      }
      this.fullscreen = !this.fullscreen;
    },

    //页面关闭时退出
    beforeunloadHandler (e) {
      // debugger
      this._beforeUnload_time = new Date().getTime()
      console.log('this._beforeUnload_time:', this._beforeUnload_time)
      e = e || window.event
      if (e) {
        e.returnValue = '关闭提示'
      }
      // debugger
      return '关闭提示'
    },
    unloadHandler () {
      console.log('this._beforeUnload_time2:', this._beforeUnload_time)
      this._gap_time = new Date().getTime() - this._beforeUnload_time
      console.log('this._gap_time:', this._gap_time)
      // 判断是窗口关闭还是刷新
      if (this._gap_time <= 2) {
        // debugger
        // 如果是登录状态，关闭窗口前，移除用户
        if (!this.showLoginButton) {
          localStorage.removeItem("token");
        }
      } else {
        // debugger
      }

    },
  },
  mounted() {
    if (document.body.clientWidth < 1500) {
      this.collapseChage();
    }
    window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
    window.addEventListener('unload', e => this.unloadHandler(e))
  },
  destroyed () {
    window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
    window.removeEventListener('unload', e => this.unloadHandler(e))
  },

};
</script>
<style scoped>
.updateinfo {
  height: 350px;
  overflow: auto;
}

.left {
  /* width: 330px; */
  float: left;
}

.right {
  overflow: hidden;
}

.header {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: 70px;
  font-size: 22px;
  color: #fff;
}

.collapse-btn {
  float: left;
  padding: 0 21px;
  cursor: pointer;
  line-height: 70px;
}

.header .logo {
  float: left;
  width: 300px;
  line-height: 70px;
  /* font-family: 'A023';
  font-family: 'LMQY'; */
}

.time {
  font-family: A023;
  float: left;
  line-height: 70px;
}

.header-right {
  float: right;
  padding-right: 50px;
}

.header-user-con {
  display: flex;
  height: 70px;
  align-items: center;
}

.btn-fullscreen {
  transform: rotate(45deg);
  margin-right: 5px;
  font-size: 24px;
}

.btn-bell,
.btn-fullscreen {
  position: relative;
  width: 30px;
  height: 30px;
  text-align: center;
  border-radius: 15px;
  cursor: pointer;
}

.btn-bell-badge {
  position: absolute;
  right: 0;
  top: -2px;
  width: 8px;
  height: 8px;
  border-radius: 4px;
  background: #f56c6c;
  color: #fff;
}

.btn-bell .el-icon-bell {
  color: #fff;
}

.user-name {
  margin-left: 10px;
}

.user-avator {
  margin-left: 20px;
}

.user-avator img {
  display: block;
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.el-dropdown-link {
  color: #fff;
  cursor: pointer;
}

.el-dropdown-menu__item {
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
